package com.ddwl.message.service;

import com.ddwl.common.util.BeanConverUtils;
import com.ddwl.message.model.Advisory;
import com.ddwl.message.repository.AdvisoryRepository;
import com.ddwl.schema.bo.base.PageBo;
import com.ddwl.schema.bo.message.AdvisoryBo;
import com.ddwl.schema.vo.base.PageVo;
import com.ddwl.schema.vo.message.AdvisoryVo;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import java.time.Instant;
import java.util.stream.Collectors;

/**
 * @author Fu Zhaohui
 */
@Service
@RequiredArgsConstructor
public class AdvisoryService {

    private final AdvisoryRepository advisoryRepository;

    public void save(AdvisoryBo bo) {
        Advisory entity = new Advisory();
        BeanUtils.copyProperties(bo, entity);
        entity.setGmtCreated(Instant.now());
        advisoryRepository.save(entity);
    }

    public PageVo<AdvisoryVo> page(PageBo<AdvisoryBo> pageBo) {
        PageVo pageVo = new PageVo();
        BeanUtils.copyProperties(pageBo, pageVo);
        Advisory advisory = new Advisory();
        Example<Advisory> example = Example.of(advisory, ExampleMatcher.matching());
        Page<Advisory> pageable = advisoryRepository.findAll(example, PageRequest.of(pageBo.getPage() - 1, pageBo.getPageSize()));
        pageVo.setTotal(pageable.getTotalElements());
        pageVo.setData(pageable.getContent().stream().map(item -> BeanConverUtils.convertBean(item, AdvisoryVo.class)).collect(Collectors.toList()));
        return pageVo;
    }
}
